package com.baselibrary.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import java.util.List;

/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2017/7/22
 *     desc  : 懒加载
 *     revise: 懒加载时机：onCreateView()方法执行完毕 + setUserVisibleHint()方法返回true
 * </pre>
 */
public abstract class BaseLazyFragment extends BaseFragment {
    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见
    private boolean isDataLoaded; // 数据是否已请求
    protected boolean isNeedCheckLoaded;//false:每次都请求

    public BaseLazyFragment(boolean isNeedCheckLoaded) {
        this.isNeedCheckLoaded = isNeedCheckLoaded;
    }

    /**
     * 第一次可见时触发调用,此处实现具体的数据请求逻辑
     */
    protected abstract void lazyLoadData();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }
/*

    */
/**
     * 保证在initData后触发
     *//*

    @Override
    public void onResume() {
        super.onResume();
        isViewCreated = true;
        tryLoadData();
    }
*/

    /**
     * ViewPager场景下，判断父fragment是否可见
     */
    private boolean isParentVisible() {
        Fragment fragment = getParentFragment();
        return fragment == null;
    }

    /**
     * ViewPager场景下，当前fragment可见时，如果其子fragment也可见，则让子fragment请求数据
     */
    private void dispatchParentVisibleState() {
        FragmentManager fragmentManager = getChildFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        if (fragments.isEmpty()) {
            return;
        }
    }

    public void tryLoadData() {
        if (isNeedCheckLoaded) {
            if (isViewCreated && isVisibleToUser && isParentVisible() && !isDataLoaded) {
                lazyLoadData();
                isDataLoaded = true;
                //通知子Fragment请求数据
                dispatchParentVisibleState();
            }
        } else {
            if (isViewCreated && isVisibleToUser && isParentVisible()) {
                lazyLoadData();
                //通知子Fragment请求数据
                dispatchParentVisibleState();
            }
        }
    }
}